from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
from bs4 import BeautifulSoup
import re
#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def getCookies():


    headers = {
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
    }

    proxies = {
        "http": "http://qf:qf3.1415@58.194.172.216:10086/"
    }
    s = requests.session()
    s.get('http://dh.ersjk.com/spring/front/search', headers=headers,proxies = proxies)
    requests.cookies.RequestsCookieJar()  # 利用RequestsCookieJar获取

    cookies = s.cookies.get_dict()

    return cookies


def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")

    trs = soup.select(".g_tb")

    page_number2 = soup.select("#jieguo_info")[0].text

    for tr in trs:


        tempData = resultData()

        tempData["websiteType"] = 1

        try:
            tempData["titleName"] = tr.select(".l_bn_2 > a")[0].text.strip()
        except:
            raise

        try:
            tempData["author"] = [tr.select("tr")[-2].text.strip()]

        except:
            pass

        allData.append(tempData)

    return allData

def buildingParameters(data):
    # 主题、题名或关键词、题名、第一作者、作者单位、作者、关键词、摘要、基金、DOI
    # 主题:()*作者:()
    typeCorr = {
        "SU": "主题",
        "TI": "题名",
        "AU": "作者",
        "AF": "作者单位",
        "AB": "摘要",
        "KY": "关键词",
    }
    logCorr = {
        "and": "*",
        "or": "+",
        "not": "^",
        "###":"###"
    }

    data["log"].append("###")

    tempStr = []
    for i in range(len(data["values"])):

        try:
            strr = typeCorr[data["type"][i]] + ":" + "(" + data["values"][i] + ")" + "{}".format(logCorr[data["log"][i]])
            tempStr.append(strr)
        except:
            continue

    strr = ''
    for value in tempStr:
        strr += value

    return strr.strip().strip("#").strip()


def getData(cookies,keyword):

    headers = {
        'Proxy-Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Origin': 'http://dh.ersjk.com',
        'Upgrade-Insecure-Requests': '1',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://dh.ersjk.com/jsp/front/prodlist.jsp',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    data = {
        'skeyword': '',
        'sgl': '1',
        'sglbk': '1',
        'sbname': keyword,
        'sauthor': '',
        'syear': '\u6240\u6709\u6642\u4EE3',
        'sbanben': '',
        'sprod': '1003',
        'sset': '0',
        'num': '60'
    }

    proxies = {
        "http": "http://qf:qf3.1415@58.194.172.216:10086/"
    }

    response = requests.post('http://dh.ersjk.com/spring/front/search', headers=headers, cookies=cookies, data=data,proxies = proxies)

    result= formData(response)

    return result

def index(request):
    data = json.loads(request.POST.get('data', '1'))
    # paramStrs = buildingParameters(data)
    cookies = getCookies()

    allData = getData(cookies,data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")
#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.post('http://www.wanfangdata.com.cn/searchResult/getCoreSearch.do?d=0.7984447816060278', headers=headers, cookies=cookies, data=data)



